<template>
	<el-dialog
	  title="分发"
	  :visible.sync="visible"
	  :before-close="close"
	  :close-on-click-modal="false"
    append-to-body
	  width="70%">
    注：此操作会记录在《样品接收与分发记录》，并确认以下说明
    <el-tooltip effect="dark" :content="isFullLast ? '不填充' : '自动填充'" placement="top">
      <el-switch
        :disabled="ys(dataForm.checkList.checkTypeId)"
        style="float: right;"
        v-model="isFullLast"
        @change="changeFullLast"
        active-color="#7cbd36"
        inactive-color="#ff4949"
        inactive-text="上一单">
      </el-switch>
    </el-tooltip>
	  <el-row style="margin-top: 5px;">
	    <el-col :span="24">
        <el-card>
          <div slot="header" v-if="nowHYTItems != null && nowHYTItems != ''">
            此单拥有的每半年检测一次项目
            <el-table
              :data="nowHYTItems"
              border
              fit
              highlight-current-row
              style="width: 100%">
              <el-table-column
                prop="inspectionItemName"
                header-align="center"
                align="center"
                label="项名">
              </el-table-column>
              <el-table-column
                prop="inspectionGroupName"
                header-align="center"
                align="center"
                label="小组">
              </el-table-column>
              <el-table-column
                header-align="center"
                align="center"
                label="前7月历史记录">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="showHYTHistory(scope.$index)">{{ scope.row.historyHYTItems.length }}次</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <el-form label-width="100px">
            <el-form-item>
              确定分发
              <span class="font-highlight">
                <!-- 分类，品名 -->
                <span>【{{dataForm.checkList.checkTypeName}}】{{dataForm.checkList.productName}}</span>
                <span>(</span>
                <!-- 批号 -->
                <span>批号：{{dataForm.checkList.batchNum}}</span>
                <!-- 规格 -->
                <span v-if="dataForm.checkList.productSpec != null && dataForm.checkList.productSpec != ''">,规格：<span v-html="dataForm.checkList.productSpec" /></span>
                <!-- 包装规格 -->
                <span v-if="dataForm.checkList.productPackSpec != null && dataForm.checkList.productPackSpec != ''">,包装规格：{{dataForm.checkList.productPackSpec}}</span>
                <!-- 请验目的 -->
                <span>,请验目的：{{testWay(dataForm.checkList.isTest)}}</span>
                <span>)</span>
              </span>
              给以下小组：
            </el-form-item>
            <el-col :offset="5" :span="15">
              <el-form-item label="分发日期：">
                <el-date-picker
                  v-model="dataForm.dispense.dispenseDate"
                  align="right"
                  type="date"
                  placeholder="分发日期"
                  :clearable="false"
                  style="width: 100%;"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd HH:mm:ss">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :offset="5" :span="15">
              <el-form-item label="剩余量：">
                <div style="font-size: 20px">
                  <span :style="{'color': dataForm.receive.surplusQuantity >= 0 ? '#409EFF' : '#F56C6C'}">{{ dataForm.receive.surplusQuantity }}</span>
                  &nbsp;&nbsp;&nbsp;
                  <span>{{ dataForm.receive.receiveUnitName }}</span>
                  <span v-if="dataForm.info != ''">&nbsp;&nbsp;&nbsp;{{dataForm.info}}</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :offset="5" :span="15">
              <el-form-item v-for="(item, index) in dataForm.groupGets" :key="index" :label="item.inspectionGroupName + '：'" :prop="'groupGets.' + index + 'groupGetQuantity'">
                <el-input :disabled="ys(dataForm.checkList.checkTypeId)" placeholder="分发量" v-model="item.groupGetQuantity" @change="changeGroupGetQuantity(item)">
                  <template slot="append">{{ item.groupGetUnitName }}</template>
                </el-input>
              </el-form-item>
              <el-button v-if="dataForm.checkList.isTest == 0 && addGroup" @click="add" style="margin-bottom: 20px;float: right;" type="warning" class="pan-btn warning-btn">+ 留样和稳考</el-button>
              <el-button v-else @click="subtract" style="margin-bottom: 20px;float: right;" type="warning" class="pan-btn warning-btn">- 留样和稳考</el-button>
            </el-col>
          </el-form>
        </el-card>
      </el-col>
	  </el-row>

    <el-dialog
      v-if="historyVisible"
      :title="waiteItem.inspectionItemName+'的前7月历史记录'"
      :visible.sync="historyVisible"
      :before-close="closeHistory"
      append-to-body
      width="50%">
      <el-card>
        <div slot="header">
          本单信息：
        </div>
        <el-form>
          <el-form-item label="货品名称:">
            {{ dataForm.checkList.productName }}
          </el-form-item>
          <el-form-item label="物料编码:">
            {{ dataForm.checkList.productGmp }}
          </el-form-item>
          <el-form-item label="生产企业:">
            {{ yfbList.manufacturerName }}
          </el-form-item>
          <el-form-item label="删除此单的:">
            <el-button type="primary" class="pan-btn danger-btn" @click="deleteItem">{{ waiteItem.inspectionItemName }}</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-table
        :data="waiteItem.historyHYTItems"
        border
        fit
        highlight-current-row
        style="width: 100%">
        <el-table-column
          prop="inspectionItemName"
          header-align="center"
          align="center"
          label="项名">
        </el-table-column>
        <el-table-column
          prop="inspectionGroupName"
          header-align="center"
          align="center"
          label="小组">
        </el-table-column>
        <el-table-column
          prop="dispenseDate"
          header-align="center"
          align="center"
          label="分发时间">
          <template slot-scope="{row}">
            {{ row.dispenseDate | changeTime }}
          </template>
        </el-table-column>
        <el-table-column
          prop="productName"
          header-align="center"
          align="center"
          label="货品名称">
        </el-table-column>
        <el-table-column
          prop="productGmp"
          header-align="center"
          align="center"
          label="物料编码">
        </el-table-column>
        <el-table-column
          prop="batchNum"
          header-align="center"
          align="center"
          label="批号">
        </el-table-column>
        <el-table-column
          prop="manufacturerName"
          header-align="center"
          align="center"
          label="生产企业">
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" class="pan-btn primary-btn" @click="closeHistory">关 闭</el-button>
      </span>
    </el-dialog>

	  <span slot="footer" class="dialog-footer">
	    <el-button @click="close">取 消</el-button>
	    <el-button type="primary" class="pan-btn primary-btn" :loading="submiting" @click="submit()">确 定</el-button>
  	</span>
	</el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { getDispenseInfo,dispense,getLastCheckForDispense,updateItem,getYsQuantityInfo } from '@/api/check'
	import { CODE_OK } from '@/common/js/config'
  import { isBlank,parseTime,dateCompare } from '@/common/js/utils'
  import { isPositiveNumber } from '@/common/js/validate'
  import Calc from 'calculatorjs'
	export default {
		data() {
			return {
				visible: false,
        isFullLast: false,
        submiting: false,
        addGroup: true,
        dataForm: {
          checkList: '',
          receive: '',
          dispense: '',
          groupGets: [],
          info: '',
          cdys: []
        },
        items: [],
        checkStandardId: "",
        nowHYTItems: '',
        waiteItem: {},
        waiteId: "",
        historyVisible: false,
        yfbList: {}
			}
		},
		props: ["childDataForm"],
		created() {
			if (!isBlank(this.childDataForm)) {
        let date = new Date()
        this.dataForm.checkList = this.childDataForm
        this.getInfo()
        this.visible = true
			}
		},
    computed: {
      ...mapGetters([
         'userInfo'
      ])
    },
	methods: {
      deleteItem() {
        this.$confirm('确定删除此项目?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.items.splice(this.waiteId,1)
          const data = {
            isAllTest: 1,
            list: this.dataForm.checkList,
            checkStandardId: this.checkStandardId,
            items: this.items
          }
          updateItem(data).then(res => {
            if (res.code === CODE_OK) {
              this.$message.success("删除成功")
              this.close()
            }else{
              this.$message.error(res.msg)
            }
          })
        }).catch(() => {})
      },
      closeHistory() {
        this.historyVisible = false
      },
      showHYTHistory(i) {
        if (this.nowHYTItems[i].historyHYTItems.length == 0) {
          this.$message.error("此项目7月内无版检验记录")
        }
        this.waiteId = i
        this.waiteItem = this.nowHYTItems[i]
        this.historyVisible = true
      },
      changeFullLast() {
         if (this.isFullLast) {
           let content = null
           if (this.dataForm.checkList.checkTypeId == 1 || this.dataForm.checkList.checkTypeId == 2 || this.dataForm.checkList.checkTypeId == 3) {
             content = 'yfb'
           }else if(this.dataForm.checkList.checkTypeId == 4 || this.dataForm.checkList.checkTypeId == 5) {
             content = 'zc'
           }else if(this.dataForm.checkList.checkTypeId == 6) {
             content = 'wk'
           }else if(this.ys(this.dataForm.checkList.checkTypeId)) {
             content = 'ys'
           }
           const params = {
             content: content,
             checkId: this.dataForm.checkList.checkId,
             productId: this.dataForm.checkList.productId,
             isTest: this.dataForm.checkList.isTest
           }
           getLastCheckForDispense(params).then(res => {
             if (res.code === CODE_OK) {
               let lastGroupGets = res.groupGets
               for (let last of lastGroupGets) {
                 if (this.addGroup && last.inspectionGroupId == 1) {
                   this.addGroup = false
                   let arr = res.sarGroupGets.map(item => {
                     item.groupGetUnitId = this.dataForm.receive.receiveUnitId
                     item.groupGetUnitName = this.dataForm.receive.receiveUnitName
                     return item
                   })
                   for (let item of arr) {
                     this.dataForm.groupGets.push(item)
                   }
                 }
                 for (let i=0,j=this.dataForm.groupGets.length; i<j; i++) {
                   if (last.inspectionGroupId == this.dataForm.groupGets[i].inspectionGroupId) {
                     this.dataForm.groupGets[i].groupGetQuantity = last.groupGetQuantity
                   }
                 }
               }
               this.computeSurplus()
             }else{
               this.$message.error(res.msg)
               this.isFullLast = false
             }
           })
         }else{
           //初始化

         }
      },
      getInfo() {
        const params = {
          checkId: this.dataForm.checkList.checkId,
          checkTypeId: this.dataForm.checkList.checkTypeId,
          isTest: this.dataForm.checkList.isTest
        }
        getDispenseInfo(params).then(res => {
          if (res.code === CODE_OK) {
            this.dataForm.receive = res.info.receive
            this.dataForm.receive.surplusQuantity = this.dataForm.receive.receiveQuantity
            let unitId = this.dataForm.receive.receiveUnitId
            let unitName = this.dataForm.receive.receiveUnitName
            this.dataForm.groupGets = res.info.groupGets.map(item => {
              item.groupGetUnitId = unitId
              item.groupGetUnitName = unitName
              return item
            })
            if (this.dataForm.checkList.isTest == 2) {
              this.dataForm.groupGets.splice(0,1)
            }
            if (res.info.standard != null) {
              this.checkStandardId = res.info.standard.checkStandardId
              this.items = res.info.items
            }
            if (res.info.nowHYTItems != null) {
              this.nowHYTItems = res.info.nowHYTItems
            }
            if (res.info.yfbList != null) {
              this.yfbList = res.info.yfbList
            }
            this.dataForm.dispense = res.info.dispense
            this.dataForm.dispense.checkId = this.dataForm.checkList.checkId
            this.dataForm.dispense.dispenseQuantity = 0
            this.dataForm.dispense.dispenseUnitId = unitId
            this.dataForm.dispense.dispenseUnitName = unitName
            this.dataForm.dispense.dispenseUserId = this.userInfo.userId
            this.dataForm.dispense.dispenseUserName = this.userInfo.name
            if (this.ys(this.dataForm.checkList.checkTypeId)) {
              const params = {
                checkId: this.dataForm.checkList.checkId
              }
              getYsQuantityInfo(params).then(res => {
                if (res.code === CODE_OK) {
                  this.dataForm.info = res.info
                  this.dataForm.cdys = res.wqs.map(w => {
                    this.$set(w,'diCount', w.count)
                    return w
                  })
                  for (let g of this.dataForm.groupGets) {
                    for (let cdy of this.dataForm.cdys) {
                      if (cdy.inspectionGroupId == g.inspectionGroupId) {
                        if (g.groupGetQuantity == null) {
                          g.groupGetQuantity = 0
                        }
                        g.groupGetQuantity = Calc.add(g.groupGetQuantity, Calc(cdy.waterQuantity + '*' + cdy.diCount))
                      }
                    }
                  }
                  this.computeSurplus()
                }else{
                  this.$message.error(res.msg)
                }
              })
            }
          }else{
          	this.$message.error(res.msg)
          }
        })
      },
      changeGroupGetQuantity(item) {
        if (item.groupGetQuantity == 0) {
          this.$message.error("分发量不能为0，若此小组多余，请查看检验项是否配置正确")
          let index = this.dataForm.groupGets.indexOf(item)
          this.dataForm.groupGets[index].groupGetQuantity = null
          return
        }
        if(!isPositiveNumber(item.groupGetQuantity) && !isBlank(item.groupGetQuantity)){
          this.$message.error("请输入正数")
          let index = this.dataForm.groupGets.indexOf(item)
          this.dataForm.groupGets[index].groupGetQuantity = null
          return
        }
        this.computeSurplus()
      },
      computeSurplus() {
        this.dataForm.dispense.dispenseQuantity = 0
        for (let i=0,j=this.dataForm.groupGets.length; i<j; i++) {
          if (!isBlank(this.dataForm.groupGets[i].groupGetQuantity)) {
            this.dataForm.dispense.dispenseQuantity = Calc.add(this.dataForm.dispense.dispenseQuantity,this.dataForm.groupGets[i].groupGetQuantity)
          }
        }
        this.dataForm.receive.surplusQuantity = Calc.sub(this.dataForm.receive.receiveQuantity,this.dataForm.dispense.dispenseQuantity)
      },
      add() {
        this.addGroup = false
        const params = {
          checkId: this.dataForm.checkList.checkId,
          isTest: 1
        }
        getDispenseInfo(params).then(res => {
          if (res.code === CODE_OK) {
            let arr = res.info.groupGets.map(item => {
              item.groupGetUnitId = this.dataForm.receive.receiveUnitId
              item.groupGetUnitName = this.dataForm.receive.receiveUnitName
              return item
            })
            for (let item of arr) {
              this.dataForm.groupGets.push(item)
            }
          }else{
          	this.$message.error(res.msg)
          }
        })
      },
      subtract() {
        this.addGroup = true
        this.dataForm.groupGets.splice(this.dataForm.groupGets.length - 2,2)
        this.changeGroupGetQuantity({groupGetQuantity: 666})
      },
			close(val) {
				this.$emit('close')
				if (val == 'submit') {
				  this.$emit('refreshData')
				}
				this.visible = false
			},
			submit() {
        if (this.formVerify()) {
          this.submiting = true
          const data = {
            dispense: this.dataForm.dispense,
            groupGets: this.dataForm.groupGets.filter(item => {
              return !isBlank(item.groupGetQuantity)
            }),
            surplusQuantity: this.dataForm.receive.surplusQuantity
            //未使用,当需要记录小组领取瓶数时，再使用
            // cdys: this.dataForm.cdys
          }
          dispense(data).then(res => {
            if (res.code === CODE_OK) {
              this.$message({
                message: '提交成功',
                type: 'success',
                duration: 1500
              })
              this.close("submit")
            }else{
              this.submiting = false
              this.$message.error(res.msg)
            }
          })
        }
			},
      formVerify() {
        if (isBlank(this.dataForm.dispense.dispenseDate)) {
          this.$message.error("请选择分发日期")
          return false
        }
        if (!dateCompare(this.dataForm.receive.receiveDate, this.dataForm.dispense.dispenseDate)) {
          this.$message.error("分发日期必须晚于收样日期")
          return false
        }
        if (this.dataForm.receive.surplusQuantity < 0) {
          this.$message.error("剩余量不够分了哦")
          return false
        }
        if (this.dataForm.checkList.isTest == 1) {
          if (isBlank(this.dataForm.groupGets[0].groupGetQuantity) && isBlank(this.dataForm.groupGets[1].groupGetQuantity)) {
            this.$message.error("留样室和稳考室必须分发一个")
            return false
          }
        }else if(this.dataForm.checkList.isTest == 0){
          for (let item of this.dataForm.groupGets) {
            if (isBlank(item.groupGetQuantity) && item.inspectionGroupName != '留样室' && item.inspectionGroupName != '稳考室') {
              this.$message.error("所有检验组的分发量均不能为空")
              return false
            }
          }
        }
        return true
      }
    }
	}
</script>

<style scoped>
  >>> .el-form-item__content {
    line-height: 40px !important;
  }
</style>
